<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item :to="{ name: 'ExamineeList' }"
            >考生列表</el-breadcrumb-item
          >
          <el-breadcrumb-item>{{ pageTitle }}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="add_examinee_content">
        <!-- 表单 -->
        <el-row>
          <el-col :span="24">
            <el-form
              ref="submitFrom"
              :model="submitData"
              label-width="100px"
              :rules="rules"
              :disabled="editKey == 3"
            >
              <el-form-item label="证件照" size="small" prop="person_photo">
                <el-col :span="6">
                  <el-upload
                    class="add_examinee_uploader"
                    :data="uploadData"
                    :action="actionUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :headers="headers"
                  >
                    <img
                      v-if="imageShowUrl"
                      :src="imageShowUrl"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-col>
              </el-form-item>

              <el-form-item label="考生姓名" size="small" prop="name">
                <el-col :span="6">
                  <el-input v-model="submitData.name" maxlength="10"></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="性别" size="small" prop="gender">
                <el-col :span="6">
                  <el-select
                    v-model="submitData.gender"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-col>
              </el-form-item>

              <el-form-item label="证件类型" size="small" prop="identity_type">
                <el-col :span="6">
                  <el-select
                    v-model="submitData.identity_type"
                    placeholder="请选择"
                    style="width: 100%"
                    :disabled="!hasExamSecord"
                  >
                    <el-option label="身份证" value="1"></el-option>
                    <el-option label="其他" value="2"></el-option>
                  </el-select>
                </el-col>
              </el-form-item>

              <el-form-item label="证件号" size="small" prop="identity_number">
                <el-col :span="6">
                  <el-input
                    v-model="submitData.identity_number"
                    maxlength="20"
                    :disabled="!hasExamSecord"
                  ></el-input>
                </el-col>
              </el-form-item>

              <el-form-item label="出生日期" size="small" prop="age">
                <el-col :span="6">
                  <el-date-picker
                    v-model="submitData.age"
                    placeholder="请选择"
                    :format="format"
                    :value-format="valueFormat"
                  >
                  </el-date-picker>
                </el-col>
              </el-form-item>

              <el-form-item label="身高" size="small" prop="height">
                <el-col :span="6">
                  <el-input
                    v-model="submitData.height"
                    maxlength="3"
                  ></el-input>
                </el-col>
                <el-col :span="1">&nbsp;&nbsp;cm</el-col>
              </el-form-item>

              <el-form-item label="篮球等级" size="small" prop="level">
                <el-col :span="6">
                  <el-select
                    v-model="submitData.level"
                    placeholder="请选择"
                    style="width: 100%"
                    :disabled="!hasExamSecord"
                  >
                    <el-option label="无" :value="0"></el-option>
                    <el-option
                      v-for="item in levelList"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-row>
    <div class="add_examinee_btn_box" v-if="editKey != 3">
      <el-button
        type="danger"
        size="mini"
        icon="iconfont icon-bg-save"
        @click="saveBtn()"
        class="save_btn"
        >保存</el-button
      >
      <el-button
        type="info"
        size="mini"
        icon="iconfont icon-w_fanhui"
        @click="backBtn()"
        >返回上一页</el-button
      >
    </div>
    <div class="add_examinee_btn_box" v-else>
      <el-button
        type="danger"
        size="mini"
        icon="iconfont icon-w_fanhui"
        @click="backBtn()"
        >返回</el-button
      >
    </div>
  </div>
</template>
<style src="../../assets/css/examinee/examineeFrom.css" scoped></style>

<script>
export default {
  name: "ExamineeFrom",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl, //默认路径
      actionUrl: this.$store.state.baseAPIUrl + "/upload/uploadFile", // 上传路径
      imageShowUrl: "", // 预览路径
      uploadData: {
        source: 1,
      }, // 上传额外参数
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      examineeId: "", // 考生id
      pageTitle: "", // 页面名称
      editKey: 0, // 是否编辑
      submitData: {
        name: "",
        person_photo: "",
        gender: "",
        identity_type: null,
        identity_number: "",
        age: "",
        height: "",
        level: "",
      }, // 提交数据
      rules: {
        person_photo: [
          { required: true, message: "请输入上传证件照", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入考生名称", trigger: "blur" }],
        gender: [
          { required: true, message: "请选择考生性别", trigger: "change" },
        ],
        identity_type: [
          { required: true, message: "请选择证件类型", trigger: "change" },
        ],
        identity_number: [
          { required: true, validator: this.validateIdentity_number },
        ],
        age: [
          {
            required: true,
            message: "请选择出生日期",
            trigger: "change",
          },
        ],
        height: [{ required: true, validator: this.validateHeight }],
        level: [
          { required: true, message: "请选择考生等级", trigger: "change" },
        ],
      }, // 校验规则
      format: "yyyy 年 MM 月 dd 日",
      valueFormat: "yyyy-MM-dd",
      levelList: [], // 等级列表
      loadingKey: false,
      loadingText: "",
      hasExamSecord: true, // 考生是否可编辑等级
    };
  },
  created: function () {
    let examineeId = this.$route.params.id;
    let editKey = this.$route.params.key;
    if (examineeId != undefined && examineeId != "") {
      this.$store.commit("set_editExamineeId", examineeId);
      this.examineeId = examineeId;
    } else {
      this.examineeId = this.$store.state.editExamineeId;
    }

    if (editKey != undefined && editKey != "") {
      this.$store.commit("set_editExamineeKey", editKey);
      this.editKey = editKey;
    } else {
      this.editKey = this.$store.state.editExamineeKey;
    }

    if (this.editKey == 2) {
      this.pageTitle = "编辑考生";
    } else if (this.editKey == 1) {
      this.pageTitle = "添加考生";
      this.$store.commit("set_editExamineeId", "");
      this.examineeId = "";
    } else {
      this.pageTitle = "查看考生";
    }
    if (this.editKey != 1 && this.examineeId != false) {
      this.getDataFn();
    }
    this.levelList = JSON.parse(JSON.stringify(this.$store.state.levelList));
  },
  methods: {
    // 查询考生信息
    getDataFn: function () {
      let that = this;
      let url = "/mobile/studentDetail";
      let data = {
        stu_id: this.examineeId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.submitData = {
              name: response.stu_info.name,
              person_photo: response.stu_info.person_photo,
              gender: response.stu_info.gender,
              identity_number: response.stu_info.identity_number,
              identity_type: response.stu_info.identity_type,
              age: response.stu_info.age,
              height: response.stu_info.height,
              level: response.stu_info.real_level,
            };
            if (response.stu_info.exist_exam_record == 1) {
              that.hasExamSecord = true;
            } else {
              that.hasExamSecord = false;
            }
            if (
              response.stu_info.identity_type != 1 &&
              response.stu_info.identity_type != 2
            ) {
              that.submitData.identity_type = 2;
            }
            if (
              response.stu_info.gender != "男" &&
              response.stu_info.gender != "女"
            ) {
              that.submitData.gender = "男";
            }
            if (
              response.stu_info.person_photo != "" &&
              response.stu_info.person_photo != null &&
              response.stu_info.person_photo != undefined
            ) {
              that.imageShowUrl =
                that.baseAPIUrl + response.stu_info.person_photo;
            } else {
              that.imageShowUrl = "";
            }
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 提交保存
    saveBtn: function () {
      let that = this;
      let url = "";
      let data = {};
      if (this.editKey == 1) {
        url = "/mobile/addStudent";
        data = {
          name: this.submitData.name,
          person_photo: this.submitData.person_photo,
          gender: this.submitData.gender,
          identity_type: this.submitData.identity_type,
          identity_number: this.submitData.identity_number,
          age: this.submitData.age,
          height: this.submitData.height,
          level: this.submitData.level,
        };
      } else {
        url = "/mobile/editStudent";
        data = {
          stu_id: this.examineeId,
          name: this.submitData.name,
          person_photo: this.submitData.person_photo,
          gender: this.submitData.gender,
          identity_type: this.submitData.identity_type,
          identity_number: this.submitData.identity_number,
          age: this.submitData.age,
          height: this.submitData.height,
          level: this.submitData.level,
        };
      }
      this.$refs.submitFrom.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          this.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                that.$message.success("保存成功");
                that.backBtn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 返回上一页
    backBtn: function () {
      this.$router.go(-1);
    },
    // 上传成功钩子
    handleAvatarSuccess: function (res, file) {
      this.imageShowUrl = URL.createObjectURL(file.raw);
      this.submitData.person_photo = res.file_path;
      this.$message.success("上传成功");
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let that = this;
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt3M = file.size / 1024 / 1024 < 3;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        return false;
      }
      return (
        (isJPG || isPNG) &&
        isLt3M &&
        new Promise(function (resolve, reject) {
          let img = new Image();
          let fileBlobName = null;
          if (window.createObjectURL !== undefined) {
            fileBlobName = window.createObjectURL(file);
          } else if (window.URL !== undefined) {
            fileBlobName = window.URL.createObjectURL(file);
          } else if (window.webkitURL !== undefined) {
            fileBlobName = window.webkitURL.createObjectURL(file);
          }
          img.src = fileBlobName;
          img.onload = () => {
            const cl = img.height / img.width;
            if (cl >= 1.28 && cl <= 1.52) {
              resolve();
            } else {
              that.$message.error("照片尺寸不合规");
              reject();
            }
          };
        })
      );
    },
    // 校验身份证
    validateIdentity_number: function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入证件号"));
      } else if (this.submitData.identity_type == 1) {
        let telText =
          /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/;
        if (!telText.test(value)) {
          callback(new Error("身份证号格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 校验身高格式
    validateHeight: function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入身高"));
      } else {
        let telText = /[1-9]\d{1,2}\d/;
        if (!telText.test(value)) {
          callback(new Error("身高格式不正确"));
        } else {
          callback();
        }
      }
    },
  },
};
</script>
